layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    var config = {
        elem: '#operationLog',
        url: '/compBill/getCompBillList',
        cellMinWidth: 150,
        page: true,
        height: "full-125",
        limit: 10,
        totalRow: true, //开启合计行
        limits: [10, 15, 20, 25, 100, 200, 300],
        id: "operationLog",
        cols: [[
        	{ field: 'source', title: '平台',align: "center",templet: function(item){
        		/*var img = '';
        		if(item.isRefund == 1){
        			img = '<img src="/resources/images/refund.png">'
        		}*/
        		if(item.source =="2"||item.source=="3"){
        			return '<span style="color:green;">微信</span>' 
        		}else if(item.source =="4"||item.source=="5"){
        			return '<span style="color:#39a2ec;">支付宝</span>' 
        		}
        	}},
        	//{field: 'openId', title: '付款 人', align: "center", totalRowText: '合计：'},
            {field: 'caseNoBuy', minWidth: 230, title: '位置(储物柜)',align: "center",totalRowText: '合计：',templet: function(d){
                var str="";
                if(isNotNull(d.place)||isNotNull(d.caseNoBuy)){
                    var str="";
                    var caseNoBuy="";
                    if(isNotNull(d.caseNoBuy)){
                        str="号柜";
                        caseNoBuy=d.caseNoBuy;
                    }
                    return  d.place +'<span style="color:#FF5722;margin-left:6px">'+ caseNoBuy +'</span>'+str
                }else{
                    return  d.caseNo
                }
            }},
            {field: 'payAmount', title: '收款金额', align: 'center', totalRow: true},
            {field: 'serviceCharge', title: '手续费', align: 'center', totalRow: true},
            {field: 'payTime', title: '收款时间', align: 'center'},
            {field: 'compName', title: '公司名称', align: 'center'},
            {title: '操作', align: "center", templet: function(d){
            	if(d.isRefund == 1){
            		return '<a class="layui-btn-sm layui-btn-disabled alreadyRefund">已退款</a>';
            	}
            	return '<a class="layui-btn layui-btn-xs" lay-event="refund">退款</a>';
            }},
        ]],
        done:function(res){
        	var payAmountTotal = 0;//统计结算后余额
        	var serviceChargeTotal = 0;
        	layui.each(res.data,function(index,d){
        		if(d.isRefund == 0){
        			payAmountTotal+=Number(d.payAmount);
        			serviceChargeTotal+=Number(d.serviceCharge);
        		}
        	})
        	//修改 结算后余额 统计单元格文本
        	this.elem.next().find('.layui-table-total td[data-field="payAmount"] .layui-table-cell').text(Number(payAmountTotal.toFixed(4)));
        	this.elem.next().find('.layui-table-total td[data-field="serviceCharge"] .layui-table-cell').text(Number(serviceChargeTotal.toFixed(4)));
        	this.elem.next().find('.layui-table-page .layui-laypage-count').text("共 "+res.count+" 条 ; 已退款 " + res.msg +" 条");
    	}
    };
    
    function accAdd(arg1,arg2){
    	if(arg1 == 0 || arg2 == 0)
    		return  Math.max(arg1,arg2)
    	var r1,r2,m;  
    	try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}  
    	try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    	if(r1 == 0 && r2 == 0)
    		return arg1 + arg2;
    	var temp = 1;
		for(var i = 0;i < Math.max(r1,r2);i++){temp+="0";}
		m = parseInt(temp);
		console.log("m: "+m+" arg1: "+arg1+" arg1*m: "+arg1*m+" arg2: "+arg2+" "+" arg2*m: "+arg2*m)
    	return (arg1 * m + arg2 * m)/m;
	} 
    
    if(!isNotNull(sessionStorage.getItem("compBill"))){
    	for (var i = 0; i < config.cols[0].length; i++) {
			if(i == config.cols[0].length-1){
		    	config.cols[0].splice(i,1);
		    	break;
			}
		}
    }
    sessionStorage.removeItem("compBill"); 
    var tableIns = table.render(config);
    //空字符串校验
    function isNotNull(obj){
        var result = true;
        switch (obj) {
            case undefined:
            case null:
                result = false;
                break;
        }
        if(result){
            if(obj.replace(/\s+/g,"") == ""){//空字符串校验
                result = false;
            }
        }
        return result;
    }
    var begin, end, keys

    $("#xls").on("click", function () {
        compId = $(".comp").val();
        $.get("/compBill/getCompBillList",{
            page:1,
            limit:tableIns.config.page.count ,
            compId:compId,
            startTime:begin,
            endTime:end
        }, function (res) {

            window.location.href = "/compBill/excel";
        })
    })

    var formatDate = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second= date.getSeconds();
        second = minute < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+ second;
    };

    $('#button').on('click', function () {
        compId = $(".comp").val();

        if(begin == ""){
            end = formatDate(new Date());
            // console.log(end)
        }
        table.reload("operationLog", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                startTime: begin,
                endTime: end,
                compId: compId
            }
        })
    });

    //执行一个laydate实例
    laydate.render({
        elem: '#begin' //指定元素
        , type: 'datetime'
        , done: function (value, date, endDate) {
            // console.log(value);
            begin = value //得到日期生成的值，如：2017-08-18
        }
    });
    laydate.render({
        elem: '#end' //指定元素
        , type: 'datetime'
        , done: function (value, date, endDate) {
            // console.log(value);
            end = value //得到日期生成的值，如：2017-08-18
        }
    });
    
    //列表操作
    table.on('tool(operationLog)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'refund') { //编辑
        	refund(data);
        }
    });
    
    function refund(parm){
    	var platform = platformFun(parm);
    	var boxPlace = boxPlaceFun(parm);
    	layer.open({
    	    id:1,
	        type: 1,
	        title:'确认退款?',
	        skin:'layui-layer-rim',
	        area:['auto', 'auto'],
	        content: '<ul class="row" style="width:300px;padding:0px 20px">'
	            +'<li class="col-sm-12">平&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;台:&nbsp;'+platform+'</li>'
	            +'<li class="col-sm-12">储&nbsp;&nbsp物&nbsp;&nbsp柜:&nbsp;'+boxPlace+'</li>'
	            +'<li class="col-sm-12">收款金额:&nbsp;'+parm.payAmount+'</li>'
	            +'<li class="col-sm-12">收款时间:&nbsp;'+parm.payTime+'</li>'
	            +'<li class="col-sm-12">公司名称:&nbsp;'+parm.compName+'</li>'
                +'</ul>'
	        ,
	        btn:['确认','取消'],
	        btn1: function (index,layero) {
	        	layer.close(index);
	        	inputRefundPassword(parm.id);
	        },
	        btn2:function (index,layero) {
	        	layer.close(index);
	        }
	    });
    }
	function inputRefundPassword(recordId){
    	var password = '';
		layer.open({
	    	id:2,
	        type: 1,
	        title:'退款密码验证',
	        skin:'layui-layer-rim',
	        area:['auto', 'auto'],
	        content: '<div class="row" style="width: 420px;  margin:7px; margin-top:10px;">'
	            +'<div class="col-sm-12">'
	            +'<div class="input-group">'
	            +'<input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="输入登录密码" class="layui-input refundPassword">'
	            +'</div>'
	            +'</div>'
                +'</div>'
	        ,
	        btn:['确认','取消'],
	        btn1: function (index,layero) {
	        	if(isNotNull(password)){
    	        	$.ajax({
    	        		url:"/compBill/refund",
    	    			type:"post",
    	    			dataType: 'json',
    	    			data:{"recordId":recordId,"password":password},
    	    			success:function(res){
    	    				layer.close(index);
    	                    layer.open({
    	                        title: '温馨提示'
    	                        ,content: res.message
    	                    });
    	                    if(res.success){
    	    					setTimeout(function(){location.reload()},200);
    	    				}
    	    			}
    	    		});
	        	}else{
    	        	layer.msg("密码不能为空");
	        	}
	        },
	        btn2:function (index,layero) {
	        	layer.close(index);
	        }
	    });
		$(".refundPassword",parent.document).keydown(function(evt){
		  	if (evt.keyCode.toString() == "8" || evt.keyCode.toString() == "46" ){
		        evt.delegateTarget.value = '';
				password = '';
				return;
			}
		});
		$(".refundPassword",parent.document).on('input',function(evt){
			var value = evt.delegateTarget.value;
		    password+=value.charAt(value.length-1);
		    evt.delegateTarget.value = value.replace(value.charAt(value.length-1),'*');
		});
    }
    //平台
    function platformFun(item){
		if(item.source =="2"||item.source=="3"){
			return '<span style="color:green;">微信</span>' 
		}else if(item.source =="4"||item.source=="5"){
			return  '<span style="color:#39a2ec;">支付宝</span>' 
		}
    }
    //储物柜位置
   function boxPlaceFun(d){
        var str="";
        if(isNotNull(d.place)||isNotNull(d.caseNoBuy)){
            var str="";
            var caseNoBuy="";
            if(isNotNull(d.caseNoBuy)){
                str="号柜";
                caseNoBuy=d.caseNoBuy;
            }
            return  d.place +'<span style="color:#FF5722;margin-left:6px">'+ caseNoBuy +'</span>'+str
        }else{
            return  d.caseNo
        }
    }
    //空字符串校验
    function isNotNull(obj){
	    var result = true;
	    switch (obj) {
	        case undefined:
	        case null:
	            result = false;
	            break;
	    }
	    if(result){
	        if(obj.replace(/\s+/g,"") == ""){//空字符串校验
	            result = false;
	        }
	    }
	    return result;
	}
})
